import {
  getCommentsService,
  getCommentService,
  postCommentService,
  patchCommentService,
  deleteCommentService,
} from '../service/index.js'

export const getComments = async ctx => {
  try {
    const query = ctx.query
    const content = ctx.query.content || ''
    const pagenum = Math.abs(Number(query.pagenum)) || 1
    const pagesize = Math.abs(Number(query.pagesize)) || 10
    const skip = (pagenum - 1) * pagesize
    const comments = await getCommentsService(content, skip, pagesize)
    ctx.body = {
      data: comments,
      message: comments.length > 0 ? '获取评论列表成功' : '评论列表为空',
    }
  } catch (err) {
    throw err
  }
}

export const getComment = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const comment = await getCommentService(id)
    ctx.body = {
      data: comment,
      message: comment ? '获取评论成功' : '此评论不存在',
    }
  } catch (err) {
    throw err
  }
}

export const postComment = async ctx => {
  try {
    const { content, postId, parentId } = ctx.request.body
    const comment = await postCommentService({
      content,
      postId: parseInt(postId),
      parentId: parentId ? parseInt(parentId) : null,
    })
    ctx.body = {
      data: comment,
      message: '创建评论成功',
    }
  } catch (err) {
    throw err
  }
}

export const patchComment = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const { content, postId, parentId } = ctx.request.body
    const comment = await patchCommentService(id, {
      content,
      postId: parseInt(postId),
      parentId: parentId ? parseInt(parentId) : null,
    })
    ctx.body = {
      data: comment,
      message: '更新评论成功',
    }
  } catch (err) {
    throw err
  }
}

export const deleteComment = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const comment = await deleteCommentService(id)
    ctx.body = {
      message: comment.count === 1 ? '删除评论成功' : '此评论不存在',
    }
  } catch (err) {
    throw err
  }
}
